package com.utc.cards.games.damedepique;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;

import com.utc.cards.R;
import com.utc.cards.model.HostModel;
import com.utc.cards.model.deck.Deck;
import com.utc.cards.model.game.Fold;
import com.utc.cards.model.game.IGame;
import com.utc.cards.model.player.HumanPlayer;
import com.utc.cards.model.player.IPlayer;
import com.utc.cards.table.view.AbstractTableGameActivity;
import com.utc.cards.table.view.TableSelectGameActivity;
import com.utc.cards.utils.Utils;

public class DameDePiqueTableGameActivity extends AbstractTableGameActivity
{

    private DrawerLayout mDrawerLayout;
    private LinearLayout mDrawerPanel;
    private ActionBarDrawerToggle mDrawerToggle;
    private FragmentDameDePiqueTableGameActivity mContentFrame;

    private boolean displayScore = true;

    @Override
    public int getLayout()
    {
        return R.layout.activity_dame_de_pique_table_game;
    }

    @Override
    public int getMenu()
    {
        return R.menu.menu_dame_de_pique_game_host;
    }

    @Override
    public void onCreateSpecificView(Bundle savedInstanceState)
    {
        log.debug("Dame de pique: onCreateSpecificView");

        Utils.hideNavigationButtons(this);

        // Jeu de test
        // testCase();

        setSlidingMenu(savedInstanceState);
    }

    private void testCase()
    {
        // Pour tests ...
        IGame g = new DameDePique();
        IPlayer p1 = new HumanPlayer("Benoit");
        IPlayer p2 = new HumanPlayer("Arnaud");
        IPlayer p3 = new HumanPlayer("Vincent");
        IPlayer p4 = new HumanPlayer("Flo");

        p1.setDisplayColor(Color.RED);
        p2.setDisplayColor(Color.YELLOW);
        p3.setDisplayColor(Color.BLUE);
        p4.setDisplayColor(Color.GREEN);

        g.addPlayer(p1);
        g.addPlayer(p2);
        g.addPlayer(p3);
        g.addPlayer(p4);

        Deck base = g.getDeck();
        new HostModel();
        HostModel.Instance().setGame(g);

        Map<String, Deck> m = new HashMap<String, Deck>();
        Deck d = new Deck();
        d.add(base.get(0));
        m.put(p1.getName(), d);

        d = new Deck();
        d.add(base.get(1));
        m.put(p2.getName(), d);

        d = new Deck();
        d.add(base.get(2));
        m.put(p3.getName(), d);

        d = new Deck();
        d.add(base.get(3));
        m.put(p4.getName(), d);

        Fold f = new Fold(m);

        HostModel.Instance().setCurrentFold(f);

        Map<String, Integer> mapScore = new HashMap<String, Integer>();
        mapScore.put(p1.getName(), 100);
        mapScore.put(p2.getName(), 12);
        mapScore.put(p3.getName(), 21);
        mapScore.put(p4.getName(), 9);

        HostModel.Instance().getScores().setScoresByGameIndex(0, mapScore);
    }

    private void setSlidingMenu(Bundle savedInstanceState)
    {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerPanel = (LinearLayout) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer
        // opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setTitle(HostModel.Instance().getGame().getName());

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
        mDrawerLayout, /* DrawerLayout object */
        R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
        R.string.drawer_open, /* "open drawer" description for accessibility */
        R.string.drawer_close /* "close drawer" description for accessibility */
        )
        {
            public void onDrawerClosed(View view)
            {
                getActionBar().setTitle(HostModel.Instance().getGame().getName());
                invalidateOptionsMenu(); // creates call to
                                         // onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView)
            {
                getActionBar().setTitle("Options");
                invalidateOptionsMenu(); // creates call to
                                         // onPrepareOptionsMenu()
            }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);

        setContentFrame();
    }

    private void setContentFrame()
    {
        // update the main content by replacing fragments
        mContentFrame = new FragmentDameDePiqueTableGameActivity();
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, mContentFrame).commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.cards, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
        // If the nav drawer is open, hide action items related to the content
        // view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerPanel);
        menu.findItem(R.id.menu_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
        case R.id.menu_exit:
            finish();
            break;
        case R.id.menu_settings:
            mDrawerLayout.openDrawer(mDrawerPanel);
            break;

        }

        // The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item))
        {
            return true;
        }

        return false;

    }

    public void toggleScoreClick(View v)
    {
        displayScore = !displayScore;

        updateScore();
    }

    public void leaveGameClick(View v)
    {
        // Quitter la partie en cours
        // Notifier à tous les joueurs la fin de la partie

        // Retourner au menu de sélection du jeu.

        Intent intent = new Intent(this, TableSelectGameActivity.class);
        startActivity(intent);
    }

    @Override
    public void updateBoard()
    {
        if (mContentFrame != null)
        {
            mContentFrame.updateBoard(HostModel.Instance().getCurrentFold());
        }
    }

    @Override
    public void updateScore()
    {
        if (mContentFrame != null)
        {
            mContentFrame.updateScore(displayScore, HostModel.Instance().getScores().getLastPartyScore());
        }
    }

    @Override
    public void launchWinnerAnimation()
    {
        if (mContentFrame != null)
        {
            // Pour test
            HostModel.Instance().getCurrentFold().setWinner(HostModel.Instance().getGame().getPlayers().get(2));
            // Fin pour test

            mContentFrame.launchWinnerAnimation(HostModel.Instance().getCurrentFold().getWinner());
        }
    }

    @Override
    public void displayGameWinner()
    {
        if (mContentFrame != null)
        {
            IPlayer winner = getWinner();

            mContentFrame.displayGameWinner(winner);
        }
    }

    private IPlayer getWinner()
    {
        Map<String, Integer> scoreMap = HostModel.Instance().getScores().getLastPartyScore();

        IPlayer playerWithBestScore = null;
        int score = 1000;

        for (String p : scoreMap.keySet())
        {
            int playerScore = scoreMap.get(p);
            if (playerScore < score)
            {
                playerWithBestScore = HostModel.Instance().getGame().getPlayerByName(p);
                score = playerScore;
            }
        }

        return playerWithBestScore;
    }

    @Override
    public Activity getThis()
    {
        return this;
    }
}
